import datetime
import json

from flask import redirect, request, g, jsonify
from  flask_classy import FlaskView, route

from vsogame.proj import order as order_signal
from . import require_login
from ..contril import Payment
from ..models.order import Order, OrderDetail
from ..models.account_his import AccountHistory
from ..schema.object import order_schema, orders_schema
from ..schema.param import pagination_param
from ..models.inventory import Ticket
from ..models.gateway import Gateway
class OrderDetailsView(FlaskView):
    @route('/order_detail/<id>/delivery')
    def get_order_detail_delivery(self, id):
        order_detail = OrderDetail.get_or_none(OrderDetail.id == id)

        if order_detail:
            delivery_info = order_detail.delivery_info


class OrdersView(FlaskView):
    @route('/<order_id>')
    def get_by_id(self, order_id):
        order = Order.get_or_none(Order.id == order_id)

        if not order:
            pass
        else:
            return order_schema.jsonify(order)

    # @route('/<order_id>/delivery')
    # def get_order_delivery(self, order_id):
    #     pass
    #     order = Order.get_or_none(order_id)
    #
    #     if order :


    @route('/filter', methods=['POST'])
    @require_login
    def get_order_list(self):
        data, _ = pagination_param.load(request.get_json())
        member = g.member
        query_list = Order.get_by_member(member)

        count = query_list.count()

        current_page = data.get('current_page', 1)
        page_size = data.get('page_size', 10)

        return jsonify({
            'pagination': {
                'current_page': current_page,
                'page_size': page_size,
                'total': count
            },
            'items': orders_schema.dump(query_list).data
        })

    @route('/test')
    def test(self):
        return '{"a":"b"}'


class OrderResultView(FlaskView):
    @route('/')
    def on_payment_notify(self):
        payment_id = request.values.get('payment_id', None)

        if not payment_id: return 'failed'
        payment = Payment.find(resource_id=payment_id)
        order = Order.get_or_none(Order.payment_seq == payment_id)
        if not order:
            return 'failed'
        else:
            if order.is_paid(): return 'success'
        if payment:
            status = payment.status

            if status == 'success':
                # 支付成功
                order.status = Order.STATUS_PAID
            else:
                order.status = Order.STATUS_PAY_ERROR
                # 支付失败
            order.updated_at = datetime.datetime.now()
            order.payment_time = datetime.datetime.now()
            order.save()

            order_signal.order_fundin_finished.delay(order)
            order_signal.delivery(order)
            notify_info = order.notify_info

            if notify_info:
                try:
                    notify_obj = json.loads(notify_info)
                    method = notify_obj['method']

                    if method.upper() == 'REDIRECT':
                        link = notify_obj['link']
                        ref_id = notify_obj.get('ref_id', 'id')

                        return redirect('{}?{}={}'.format(link, ref_id, order.id))
                except Exception as e:
                    pass
                    return 'failed'
            else:
                return 'success'
        else:
            return 'failed'
            # TODO 发货
